package lumis.collaboration.chat;

import lumis.content.ContentStringResource;
import lumis.portal.PortalException;
import lumis.portal.UnexpectedException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.clock.ClockConfig;
import lumis.portal.service.GenericServiceClock;
import lumis.portal.service.ServiceException;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.util.IResource;
import lumis.util.ITransaction;

/**
 * Checks for expired chat rooms and inactive chat users 
 *
 * @version $Revision: 8948 $ $Date: 2008-02-29 12:40:36 -0300 (Fri, 29 Feb 2008) $
 * @since 4.0.6
 */
public class ChatClock extends GenericServiceClock
{
	protected IResource resource = new ContentStringResource();
	
	public ChatClock()
	{
		resource.addResourcePath("lumis/collaboration/chat/strings/strings");
	}

	public void doTick(SessionConfig sessionConfig, ClockConfig clockConfig) throws ServiceException, PortalException
	{
		ITransaction transaction = PortalTransactionFactory.createTransaction();
		try
		{
			transaction.begin();
			
			// take all chats that are not inactive but have expired and close them
			ChatManagerFactory.getChatManager().closeExpiredConversations(sessionConfig, transaction);
			
			// take all chats that are waiting but have started time and open them
			ChatManagerFactory.getChatManager().openStartedConversations(sessionConfig, transaction);
			
			// take all active users that have not acessed the message list for more that the timeout, and set them as inactive
			ChatManagerFactory.getChatManager().updateActiveUserState(sessionConfig, transaction);

			transaction.commit();
		}
		catch (PortalException e)
		{
			transaction.rollback();
			throw e;
		}
		catch (Exception e)
		{
			transaction.rollback();
			throw new UnexpectedException(e);
		}
		finally
		{
			transaction.dispose();
		}

	}

}
